package com.webchat.aigc.llm;

import com.webchat.aigc.service.UserService;
import com.webchat.common.enums.PromptTemplateEnum;
import com.webchat.common.helper.SseEmitterHelper;
import com.webchat.common.service.FreeMarkEngineService;
import com.webchat.domain.vo.llm.ChatCompletionMessage;
import com.webchat.domain.vo.llm.ChatMessageRole;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import com.webchat.domain.vo.response.UserBaseResponseInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 程序员王七七 https://www.coderutil.com 网站作者
 * @date 2024/10/29 13:42
 */
@Slf4j
@RefreshScope
@Service
public class GPTChatService {

    @Autowired
    private UserService userService;

    @Autowired
    private FreeMarkEngineService freeMarkEngineService;

    @Value("${llm.config.model}")
    private String model;

    /**
     * 没有设定角色时，使用默认角色
     */
    private static final String DEFAULT_GPT_ROLE = "你是一个智能助手，帮我解决一切问题。";
    private static final String DEFAULT_ROLE = "暂无签名";

    public String chat( SseEmitter sseEmitter, ChatMessageRequestVO chatMessage) {
        // 使用工厂模式，取对应的LLM服务，来完成对话
        AbstractLLMChatService abstractLLMChatService = LLMServiceFactory.getLLMService(model);
        // 获取用户发送消息内容
        String message = chatMessage.getMessage();
        // 取消息发送人、接收人信息
        String sendUserId = chatMessage.getSenderId();
        String receiverId = chatMessage.getReceiverId();
        UserBaseResponseInfoVO receiver = userService.accountInfo(receiverId);
        String gptRoleSetting = receiver.getSignature();
        if (StringUtils.isBlank(gptRoleSetting) || DEFAULT_ROLE.equals(gptRoleSetting)) {
            gptRoleSetting = DEFAULT_GPT_ROLE;
        }
        Map<String, Object> vars = new HashMap<>();
        vars.put("roleSetting", gptRoleSetting);
        vars.put("content", message);
        String prompt;
        try {
            prompt = freeMarkEngineService.getContentByTemplate(PromptTemplateEnum.ROBOT_CHAT.getPath(), vars);
        } catch (Exception e) {
            log.error("GPTChatService.chat create prompt error. sendUserId:{}, receiverId:{}, msg:{}",
                    sendUserId, receiverId, message, e);
            return null;
        }
        final List<ChatCompletionMessage> messageList = Arrays.asList(
                new ChatCompletionMessage(ChatMessageRole.SYSTEM.value(), gptRoleSetting),
                new ChatCompletionMessage(ChatMessageRole.USER.value(), prompt));
        try {
            return abstractLLMChatService.chat(sseEmitter, messageList);
        } catch (Exception e) {
            log.error("GPTChatService.chat error. sendUserId:{}, receiverId:{}, msg:{}",
                    sendUserId, receiverId, message, e);
        }
        return null;
    }
}
